<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas</title>
    <style>
        html,
        body {
            margin: 0;
        }

        #my-canvas {
            position: relative;
            top: 30px;
            left: 50%;
            margin-left: -400px;
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <canvas id="my-canvas" width='800' height='600'></canvas>
    <script>
        let myCanvas = document.querySelector("#my-canvas")
        let ctx = myCanvas.getContext('2d')
        let isDrawing = false,
            direction = true
        let lastX, lastY = 0
        let hue = 0
        ctx.strokeStyle = '#BADA55'
        ctx.lineJoin = 'round'
        ctx.lineCap = 'round'
        ctx.lineWidth = 5

        function drawPaint(e) {
            if (isDrawing) {
                ctx.strokeStyle = `hsl(${hue},100%,50%)`;
                ctx.beginPath();
                ctx.moveTo(lastX, lastY)
                ctx.lineTo(e.offsetX, e.offsetY);
                ctx.stroke();
                [lastX, lastY] = [e.offsetX, e.offsetY]
                hue++
                if (hue >= 360) {
                    hue = 0
                }
                if (ctx.lineWidth >= 100 || ctx.lineWidth < 5) {
                    direction = !direction
                }
                if (direction) {
                    ctx.lineWidth++
                } else {
                    ctx.lineWidth--
                }
                console.log(ctx.lineWidth)
            }

        }
        //mousedown,给画笔沾颜色
        myCanvas.addEventListener('mousedown', (e) => {
            isDrawing = true;
            [lastX, lastY] = [e.offsetX, e.offsetY]

        })
        //mousemove,开始绘画
        myCanvas.addEventListener('mousemove', drawPaint)
        //mouseup,关闭画笔
        myCanvas.addEventListener('mouseup', () => isDrawing = false)
    </script>
</body>

</html>